<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               :before-close="beforeClose"
               v-model="taskForm"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @refresh-change="refreshChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot-scope="{row,type,size}" slot="menu">
        <el-button icon="el-icon-video-play" :size="size" :type="type" v-if="row.status===0" @click="startTask(row)">启动</el-button>
        <el-button icon="el-icon-video-pause" :size="size" :type="type" v-if="row.status===1" @click="closeTask(row)">关闭</el-button>
        <el-button icon="el-icon-download" :size="size" :type="type" @click="downloadRunFile(row)">下载执行文件</el-button>
      </template>
      <template slot-scope="scope" slot="cronForm">
        <el-form-item>
          <ya-cron :cronExpression.sync="cronExpression" :cronZn.sync="cronZn" v-if="showCronBox"></ya-cron>
          <span style="color: #E6A23C; font-size: 12px; height: 32px">corn从左到右（用空格隔开）：秒 分 小时 月份中的日期 月份 星期中的日期 年份</span>
          <p class="my-0">cron表达式：{{cronExpression}}</p>
          <el-input v-model="cronZn" auto-complete="off" disabled>
            <el-button slot="append" v-if="!showCronBox" icon="el-icon-arrow-up" @click="showCronBox = true" title="打开图形配置"></el-button>
            <el-button slot="append" v-else icon="el-icon-arrow-down" @click="showCronBox = false" title="关闭图形配置"></el-button>
          </el-input>
        </el-form-item>
      </template>
      <template slot-scope="scope" slot="taskFileForm">
        <avue-form :option="taskFileFormOption" :upload-after="afterTaskUpload" :upload-before="beforeTaskUpload" :upload-delete="uploadTaskDelete"> </avue-form>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
    import {mapGetters} from "vuex";
    import {getList,getDetail,add,update,remove,startTask,closeTask,removeTempTaskFile} from "@/youan/api/kettle/taskConfig";
    import yaCron from "@/youan/components/cron/cron";
    import func from "@/util/func";
    import {getToken} from '@/util/auth'

    export default {
      name: "taskConfig",
      data() {
        return {
          uploadKettleVisible: false,
          loading: true,
          taskForm: {},
          showCronBox: false,
          cronExpression: '',
          cronZn: '',
          tempTaskFileId:'',
          uploadFileNum: 0, // 上传文件的数量
          isSubmit: false, // 是否提交
          page: {
            pageSize: 10,
            currentPage: 1,
            total: 0
          },
          option:{
            tip: false,
            border: true,
            index: true,
            dialogType: 'drawer',
            dialogClickModal: false,
            menuWidth: 350,
            labelWidth: 150,
            column: [
              {
                prop: "id",
                display: false,
                showColumn: false,
                hide: true
              },
              {
                label: "定时器任务名称",
                prop: "taskName",
                display: true,
                span: 24,
                rules: [
                  {
                    required: true,
                    message: "请输入任务名称",
                    trigger: "blur"
                  }
                ]
              },
              {
                label: "任务类型",
                prop: "taskType",
                type: "select",
                span: 24,
                dicUrl: "/api/blade-system/dict-biz/dictionary?code=TASKTYPE",
                props: {
                  label: "dictValue",
                  value: "dictKey"
                },
                rules: [
                  {
                    required: true,
                    message: "请选择任务类型",
                    trigger: "change"
                  }
                ],
              },
              {
                label: "任务入口",
                prop: "taskEntry",
                display: true,
                tip: '任务入口：如果是程序请填写JAVA类路径注意需要继承JavaProgramService，如果为文件请填写主入口文件的文件名称',
                span: 24,
                rules: [
                  {
                    required: true,
                    message: "请输入执行文件",
                    trigger: "blur"
                  }
                ]
              },
              {
                label: "任务参数",
                prop: "taskParam",
                span: 24,
                hide: true
              },
              {
                label: "状态",
                prop: "status",
                type: "select",
                display: false,
                width: 120,
                formatter: (row,value) => {
                  if(value === 1) {
                    return `<span class="success">开启</span>`
                  } else if(value === 0){
                    return `<span class="warning">关闭</span>`
                  }
                },
              },
              {
                label: "来源数据源",
                prop: "fromDb",
                hide: true,
                type: "select",
                display: true,
                dicUrl: "/api/blade-system/dict-biz/dictionary?code=DBTYPE",
                props: {
                  label: "dictKey",
                  value: "dictValue"
                },
              },
              {
                label: "目标数据源",
                prop: "toDb",
                hide: true,
                type: "select",
                display: true,
                dicUrl: "/api/blade-system/dict-biz/dictionary?code=DBTYPE",
                props: {
                  label: "dictKey",
                  value: "dictValue"
                },
              },
              {
                label: "执行时间",
                prop: "cron",
                span: 24,
                showColumn: false,
                hide: true,
                display: true,
                formslot:true,
                labelslot:true,
                errorslot:true,
              },
              {
                label: "执行时间",
                prop: "taskCronzn",
                showColumn: false,
                display: false,
              },
              {
                label: "运行文件上传",
                prop: "taskFile",
                span: 24,
                hide: true,
                showColumn: false,
                display: true,
                formslot:true,
                labelslot:true,
                errorslot:true,
              },
              {
                label: "备注",
                prop: "taskRemark",
                type: "textarea",
                minRows: 8,
                span: 24,
                display: true
              },
            ]
          },
          taskFileFormOption: {
            labelWidth: 0,
            menuBtn: false,
            column: [
              {
                prop: 'flowFile',
                type: 'upload',
                loadText: '附件上传中，请稍等',
                span: 24,
                propsHttp: {
                  res: 'data'
                },
                tip: `只能上传*.kjb/*.ktr/*.zip/*.rar文件，且不超过2M,多个文件上传时请打包为zip或rar文件上传`,
                action: '/api/kettle/fileuploadtemp/save'
              },
            ]
          }
        }
      },
      computed: {
        ...mapGetters(["userInfo", "permission"]),
        permissionList() {
          return {
            addBtn: this.vaildData(this.permission.task_add, false),
            viewBtn: this.vaildData(this.permission.task_view, false),
            delBtn: this.vaildData(this.permission.task_delete, false),
            editBtn: this.vaildData(this.permission.task_modify, false)
          };
        },
      },
      watch: {
        'taskForm.taskType': {
          handler: function() {
            const taskType = func.toInt(this.taskForm.taskType);
            let isInProp = this.$makeMap('taskFile,toDb,fromDb');
            this.$refs.crud.option.column.filter(item => {
              if (isInProp(item.prop)) {
                item.display = taskType === 1 || taskType === 2;
              }
            });
          },
        }
      },
      methods: {
        beforeOpen(done, type) {
          if (["edit", "view"].includes(type)) {
            getDetail(this.taskForm.id).then(res => {
              this.taskForm = res.data.data;
              this.cronExpression = res.data.data.taskCron;
              this.cronZn = res.data.data.taskCronzn;
              // 临时解决bug 如果后台long 类型为null 前台解析成-1的问题
              this.taskForm.toDb = this.taskForm.toDb === -1 ? "" : this.taskForm.toDb;
              this.taskForm.fromDb = this.taskForm.fromDb === -1 ? "" : this.taskForm.fromDb;
            });
          }
          this.showCronBox = false;
          this.isSubmit = false;
          done();
        },
        beforeClose(done) {
          if(!this.isSubmit) {
            if(this.uploadFileNum > 0 && this.tempTaskFileId) {
              this.uploadFileNum--;
              removeTempTaskFile(this.tempTaskFileId)
            }
          }
          done();
        },
        rowSave(row, loading, done) {
          if(!this.cronExpression) {
            this.$message.error("请选择执行时间");
            done();
            return
          }
          if(row.taskType == 1 || row.taskType == 2) {
            if(!this.tempTaskFileId) {
              this.$message.error("请上传运行文件");
              done();
              return
            }
          }
          row = {
            ...row,
            taskCron: this.cronExpression,
            taskCronzn: this.cronZn,
            fileId: this.tempTaskFileId,
            // 临时解决bug 如果后台long 类型为null 前台解析成-1的问题
            toDb: row.toDb == -1? "" : row.toDb,
            fromDb: row.fromDb == -1? "" : row.fromDb,
          };
          add(row).then(() => {
            this.isSubmit = true;
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.uploadFileNum = 0;// 清空上传文件数量
          }, () => {
            done();
          });
        },
        rowUpdate(row, index, loading, done) {
          if(!this.cronExpression) {
            this.$message.error("请选择执行时间");
            done();
            return
          }
          row = {
            ...row,
            taskCron: this.cronExpression,
            taskCronzn: this.cronZn,
            fileId: this.tempTaskFileId,
            // 临时解决bug 如果后台long 类型为null 前台解析成-1的问题
            toDb: row.toDb == -1? "" : row.toDb,
            fromDb: row.fromDb == -1? "" : row.fromDb,
          };
          update(row).then(() => {
            this.isSubmit = true;
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, () => {
            done();
          });
        },
        rowDel(row) {
          this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              return remove(row.id);
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            });
        },
        selectionChange(list) {
          this.selectionList = list;
        },
        currentChange(currentPage) {
          this.page.currentPage = currentPage;
        },
        sizeChange(pageSize) {
          this.page.pageSize = pageSize;
        },
        refreshChange() {
          this.onLoad(this.page, this.query);
        },
        onLoad(page, params = {}) {
          this.loading = true;
          getList(page.currentPage, page.pageSize, Object.assign(params, this.query), this.treeDeptId).then(res => {
            const data = res.data.data;
            this.page.total = data.total;
            this.data = data.records;
            this.loading = false;
            this.selectionClear();
          });
        },
        selectionClear() {
          this.selectionList = [];
          this.$refs.crud.toggleSelection();
        },
        downloadRunFile(row) {
          if(row.taskType == 3) {
            this.$message.info("非工作和转换定时任务无法下载");
            return;
          }
          window.open(`/api/kettle/task/downloadRunFile/${row.id}?Blade-Auth=${getToken()}`);
        },
        // 上传相关代码！！！！！！！！！！！
        beforeTaskUpload(file,done,loading) {
          if(this.uploadFileNum >= 1) {
            this.$message.error('多文件请打成压缩包上传!');
            loading();
            return;
          }
          const name = file.name
          const suffix = name.substring(name.indexOf('.')+1);
          let isInTaskSuffix = this.$makeMap('zip,rar,kjb,ktr');
          let isZipSuffix = this.$makeMap('zip,rar');
          const isLt2M = file.size / 1024 / 1024 < 2;
          if(!this.taskForm.taskType) {
            this.$message.error('请先选择任务类型!');
            loading();
            return;
          }
          if (!isInTaskSuffix(suffix)) {
            this.$message.error('上传文件只能是 zip,rar,kjb,ktr 格式!');
            loading();
            return;
          }
          if(!isZipSuffix(suffix)) {
            if(this.taskForm.taskType == 1 && suffix != "kjb") {
              this.$message.error('您的任务类型为Kettle作业，请上传*.kjb文件或*.zip,*.rar文件!');
              loading();
              return;
            }

            if(this.taskForm.taskType == 2 && suffix != "ktr") {
              this.$message.error('您的任务类型为Kettle转换，请上传*.ktr文件或*.zip,*.rar文件!');
              loading();
              return;
            }
          }

          if (!isLt2M) {
            this.$message.error('上传文件大小不能超过 2MB!');
            loading();
            return;
          }
          done();
        },
        afterTaskUpload(res,done) {
          this.tempTaskFileId = res.fileId;
          this.uploadFileNum++;
          done();
        },
        uploadTaskDelete() {
          this.uploadFileNum--;
          return this.$confirm(`是否确定移除该选项？`).then(()=>{
            removeTempTaskFile(this.tempTaskFileId).then(() => {
            })
          });
        },
        startTask(row) {
          this.$confirm("确定开启定时器任务?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            startTask(row.id).then(({data}) => {
              if(data.success) {
                this.$message.success(data.msg);
              }else {
                this.$message.error(data.msg);
              }
              this.onLoad(this.page, this.query);
            });
          })
        },
        closeTask(row) {
          this.$confirm("确定关闭定时器任务?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            closeTask(row.id).then(({data}) => {
              if(data.success) {
                this.$message.success(data.msg);
              }else {
                this.$message.error(data.msg);
              }
              this.onLoad(this.page, this.query);
            });
          })
        }
      },
      components:{
        yaCron
      }
    }
</script>

<style scoped>

</style>
